package com.ostms.adv.activity;

import android.app.Activity;
import android.app.Instrumentation;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;

import com.geekmaker.paykeyboard.DefaultKeyboardListener;
import com.geekmaker.paykeyboard.IPayRequest;
import com.geekmaker.paykeyboard.PayKeyboard;
import com.geekmaker.paykeyboard.USBDetector;
import com.ostms.adv.BuildConfig;
import com.ostms.adv.service.MonitorWeixinPayService;
import com.ostms.adv.utils.LOG;

public class BaseActivity extends AppCompatActivity {
    private static final String TAG = "BaseActivity";
    public boolean isDisplayKeyBoard = false;
    public PayKeyboard keyboard;
    public USBDetector detector;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        LOG.i(TAG,"onCreate");
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        hideBottomUIMenu();
        hintKeyBoard();
        changeBottomUIMenu(this, false);

        if (PayKeyboard.get(this) != null) {
            isDisplayKeyBoard = true;
            LOG.i(TAG,"isDisplayKeyBoard = "+isDisplayKeyBoard);
        }
        detector = PayKeyboard.getDetector(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        detector.release();
    }

    @Override
    protected void onResume() {
        super.onResume();
        openKeyboard();
    }

    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 修改虚拟按键显示状态
     *
     * @param context
     * @param isBottomBarShow
     */
    private void changeBottomUIMenu(Activity context, boolean isBottomBarShow) {
        // 修改虚拟按键显示状态
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.HONEYCOMB && Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { // lower api
            View v = context.getWindow().getDecorView();
            v.setSystemUiVisibility(isBottomBarShow ? View.VISIBLE : View.GONE);
        }
        // api19之后需要做别的处理
        else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            View decorView = context.getWindow().getDecorView();
            int uiOptions = isBottomBarShow ? View.SYSTEM_UI_FLAG_VISIBLE : View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;// 需要全屏则添加上 View.SYSTEM_UI_FLAG_FULLSCREEN
            decorView.setSystemUiVisibility(uiOptions);
        }
    }

   /* @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i(TAG,"onKeyDown");
        if (keyCode == 155) {
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_HOME);
            startActivity(intent);
        }else {
            if ("qingwa".equals(BuildConfig.TARGET_CUSTOMER)) {
                onStartQingWaActivity();
                //检测是否一直停留在在青蛙支付首页的服务
                Intent monitorIntent = new Intent(this, MonitorWeixinPayService.class);
                stopService(monitorIntent);
                startService(monitorIntent);

            } else {
                Intent mIntent = this.getPackageManager().getLaunchIntentForPackage("com.ostms.wx");
                if ("ostms".equals(BuildConfig.TARGET_CUSTOMER)) {
                } else if ("yibei".equals(BuildConfig.TARGET_CUSTOMER)) {
                    mIntent = this.getPackageManager().getLaunchIntentForPackage("com.mm.ebay.facepay");//易呗经常修改临时包名，要注意临时修改！！

                } else if ("zhifu".equals(BuildConfig.TARGET_CUSTOMER)) {
                    mIntent = this.getPackageManager().getLaunchIntentForPackage("io.micent.pos.skqe");
                }
                try {
                    this.startActivity(mIntent);
                } catch (Exception e) {
                    LOG.i(TAG, "检测按键按下，找不到对应包名apk，启动apk失败");
                    e.printStackTrace();
                }
            }
        }
        return super.onKeyDown(keyCode, event);
    }*/

    private void openKeyboard() {
        if (keyboard == null || keyboard.isReleased()) {
            keyboard = PayKeyboard.get(this);
            if (keyboard != null) {
                keyboard.setListener(new DefaultKeyboardListener() {
                    @Override
                    public void onRelease() {
                        super.onRelease();
                        keyboard = null;
                        Log.i("KeyboardUI", "Keyboard release!!!!!!");
                    }

                    @Override
                    public void onAvailable() {
                        super.onAvailable();
                        // keyboard.updateSign(PayKeyboard.SIGN_TYPE_W,4);
                        Log.i("KeyboardUI", "onAvailable!!!!!");
                    }

                    @Override
                    public void onException(Exception e) {
                        Log.i("KeyboardUI", "usb exception!!!!");
                        keyboard = null;
                        super.onException(e);
                    }

                    @Override
                    public void onPay(final IPayRequest request) {
                        //super.onPay(request);
                        Log.i("KeyboardUI", "onPay!!!!");
                        sendKeyEvent(23);//自定义按键码
                    }

                    @Override
                    public void onKeyDown(final int keyCode, final String keyName) {
                        //super.onKeyDown(keyCode, keyName);
                        Log.i("KeyboardUI", "onKeyDown!!!! keyCode = " + keyCode + "  keyName = " + keyName);

                        if (keyCode == 30) {//自定义按键码
                            startActivity(new Intent(Settings.ACTION_SETTINGS)); //进入设置界面
                        }else if (keyCode == 29) {//返回主页按键
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_MAIN);
                            intent.addCategory(Intent.CATEGORY_HOME);
                            startActivity(intent);
                        } else {
                            sendKeyEvent(keyCode);
                        }

                    }


                    @Override
                    public void onKeyUp(int keyCode, String keyName) {
                        ///super.onKeyUp(keyCode, keyName);
                        Log.i("KeyboardUI", "onKeyUp!!!!");
                    }
                });
                keyboard.open();
            }
        } else {
            Log.i("KeyboardUI", "keyboard exists!!!");
        }
    }


    public static void sendKeyEvent(final int KeyCode) {//不可在主线程中调用,必须使用线程发送
        new Thread() {
            public void run() {
                try {
                    Instrumentation inst = new Instrumentation();
                    Log.i("KeyboardUI", "sendKeyEvent");
                    KeyEvent mKeyEvent = null;
                    if (KeyCode == 3) {
                        mKeyEvent = new KeyEvent(0, 33);//自定义按键码
                    } else if (KeyCode == 23) {
                        mKeyEvent = new KeyEvent(0, 501);//自定义按键码
                    } else if (KeyCode == 4) {
                        mKeyEvent = new KeyEvent(0, 44);//自定义按键码
                    } else if (KeyCode == 20) {
                        executeBackKeyFunction();
                    } else {
                        mKeyEvent = new KeyEvent(0, KeyCode);
                    }
                    Log.i("KeyboardUI", mKeyEvent.toString());
                    inst.sendKeySync(mKeyEvent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }.start();
    }

    private static void executeBackKeyFunction() {
        try {
            Runtime.getRuntime().exec("input keyevent 4");
        } catch (Exception ex) {
            Log.d("exe adb command 抛异常了", ex.getMessage());
        }
    }

    /**
     * 跳转到青蛙apk支付页面
     */
    public void onStartQingWaActivity() {
        Log.i(TAG, "onStartQingWaActivity");
        try {
            Runtime.getRuntime().exec("am start -n com.tencent.wxpayface/.lpos.home.LposActivity");
        } catch (Exception ex) {
            Log.d("exe adb command 抛异常了", ex.getMessage());
        }
    }
}
